#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

pthread_key_t key;

static void key_destrutor(void* value)
{
    printf("dest called\n"); 
    /* 这个例子中，关联key的值并没有malloc等操作，因此不用做释放动作。 */
    return (void)0;
}

int get_pspec_value_int()
{
    int* pvalue;
    pvalue = (int*)pthread_getspecific(key);
    return *pvalue;
}

void* thread_handler(void* args)
{
    int index = *((int*)args);
    int pspec;

    pspec = 0;
    /* 设置key与value的关联 */
    pthread_setspecific(key, (void*)&pspec);

    while (1)
    {
        sleep(4);
        /* 获得key所关联的value */
        pspec = get_pspec_value_int();
        printf("thread index %d = %d\n", index, pspec);
        /* 修改value的值，本例中用于测试不同线程的value不会互相干扰。 */
        pspec += index;
        pthread_setspecific(key, (void*)&pspec);
    }
    return (void*)0;
}

int main()
{
    pthread_t pid1;
    pthread_t pid2;
    int ret;
    int index1 = 1, index2 = 2;

    struct thr1_st m_thr_v, * p_mthr_v;

    /* 创建一个key */
    pthread_key_create(&key, key_destrutor);

    if (0 != (ret = pthread_create(&pid1, NULL, thread_handler, (void*)&index1)))
    {
        perror("create thread failed:");
        return 1;
    }

    if (0 != (ret = pthread_create(&pid2, NULL, thread_handler, (void*)&index2)))
    {
        perror("create thread failed:");
        return 1;
    }

    /* 设置key与value的关联 */
    memset(&m_thr_v, 0, sizeof(struct thr1_st));
    pthread_setspecific(key, (void*)&m_thr_v);

    while (1)
    {
        sleep(3);

        /* 获得key所关联的value */
        p_mthr_v = (struct thr1_st*)pthread_getspecific(key);
        printf("main len = %d\n", p_mthr_v->len);
        /* 修改value的值，本例中用于测试不同线程的value不会互相干扰。 */
        p_mthr_v->len += 5;
        pthread_setspecific(key, (void*)p_mthr_v);
    }

    /* 注销一个key */
    pthread_key_delete(key);
    pthread_join(pid1, 0);
    pthread_join(pid2, 0);

    return 0;
}